/*
 * C/C++ KLIB Project
 * 
 * Copyright (c) 2012 Ken Zhang (cpp.china@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 */


#include "klib.h"
#include <string.h>
#include <time.h>

struct _month_name_t {
	const char *short_name;
	const char *long_name;
} month_name_t;

const char *month_name(int month, int long_form)
{
	static struct _month_name_t month_names[] = {
		{ "Jan", "January" },
		{ "Feb", "February"}, 
		{ "Mar", "March" }, 
		{ "Apr", "April" }, 
		{ "May", "May" }, 
		{ "Jun", "June" }, 
		{ "Jul", "July" }, 
		{ "Aug", "August" }, 
		{ "Sep", "September" }, 
		{ "Oct", "October" }, 
		{ "Nov", "November" }, 
		{ "Dec", "December" }
	};

	if (month >= 0 && month < sizeof(month_names) / sizeof(month_name_t))
		return long_form ? month_names[month].long_name : month_names[month].short_name;
	else
		return NULL;
}


char *tmformat(char *buffer, size_t size, const char *fmt, struct tm* t)
{
	char tmp[32];

	if (size < strlen(fmt) + 1)
		return NULL;

	strcpy(buffer, fmt);
	strrep(buffer, size, "yyyy", itostr(tmp, t->tm_year + 1900, 10, 4));
	strrep(buffer, size, "mmmmm", month_name(t->tm_mon, 1));
	strrep(buffer, size, "mmm", month_name(t->tm_mon, 0));
	strrep(buffer, size, "mm", itostr(tmp, t->tm_mon + 1, 10, 2));
	strrep(buffer, size, "dd", itostr(tmp, t->tm_mday, 10, 2));
	strrep(buffer, size, "HH", itostr(tmp, t->tm_hour, 10, 2));
	strrep(buffer, size, "MM", itostr(tmp, t->tm_min, 10, 2));
	strrep(buffer, size, "SS", itostr(tmp, t->tm_sec, 10, 2));

	return buffer;
}
